package com.youmu.sichuansfc.filter.FundManager;

import com.youmu.sichuansfc.ano.FundManager.FundUserTokenUser;
import com.youmu.sichuansfc.domain.YoumuFundUser;
import com.youmu.sichuansfc.service.FundUserService;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

/**
 *  自定义 fundUser 参数注入
 * @author Administrator
 *
 */
@Component
public class FundManagerTokenUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
	
		private Logger logger = Logger.getLogger(this.getClass());


		@Autowired  
	    public FundUserService fundUserService;
	 

	  	@Override
	    public boolean supportsParameter(MethodParameter parameter) {
			logger.info(" 给tokenFundUser 赋值 开始");

			// 过滤出符合条件的参数，这里指的是加了TokenUser注解的参数
	        if (parameter.hasParameterAnnotation(FundUserTokenUser.class)) {
	            return true;
	        }
	        return false;
	    }

	    @Override
	    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                      NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
	        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

	        ServletContext sc = request.getSession().getServletContext();

			//解决Autowired为null无法注入问题
			logger.info(" fundUserService is " + fundUserService);
	        if (fundUserService == null) {
				WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getAutowireCapableBeanFactory().autowireBean(this);
				logger.info(" userService is " + fundUserService);
	        }
	        LoginInterceptor loginInterceptor = new LoginInterceptor();
			//
			YoumuFundUser user =  loginInterceptor.handlerWAWATOKEN(request, fundUserService);
			if (user != null){
				logger.info(" 给tokenFundUser 赋值 结束" + new JSONObject(user));
			}
			return user;
	    }
  

}